package com.ice.common;

import java.security.MessageDigest;

/**
 * md5加密
 * @author 潘港超
 *
 */
public class Md5Util {
	
	private  static String algorithm="MD5";
	private  static String charset="UTF-8";
	
	/**
	 * 
	 * @param source 加密的内容
	 * @return md5加密信息
	 */
	public static String md5(String source){
		MessageDigest md;
		StringBuffer sb = new StringBuffer(32);
		try {
			md = MessageDigest.getInstance(algorithm);
			md.update(source.getBytes(charset));
			
			byte[] array = md.digest();
			for(byte item : array){
				 int val = ((int)item) & 0xff;
		            if (val < 16) {
		                sb.append("0");
		            }
		            sb.append(Integer.toHexString(val));
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();
		
	}
	
	/**
	 * 
	 * @param source 加密的内容
	 * @return md5加密信息
	 */
	public static String md5(byte[] source){
		MessageDigest md;
		StringBuffer sb = new StringBuffer(32);
		try {
			md = MessageDigest.getInstance(algorithm);
			md.update(source);
			
			byte[] array = md.digest();
			for(byte item : array){
				 int val = ((int)item) & 0xff;
		            if (val < 16) {
		                sb.append("0");
		            }
		            sb.append(Integer.toHexString(val));
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();
		
	}
	/**
	 * 
	 * @param src  待检测加密的信息
	 * @param source 加密过的信息
	 * @return
	 */
	public static boolean validMd5(String src,String source){
		return src.equals(source);
	}
	/**
	 * 测试
	 * @param args
	 */
	public   static void main(String[] args) {
		String info = "明文信息";
		String source = "8091a93d83c433d93f7eb0b0a3c66d52";
		//加密
		String securityInfo = Md5Util.md5(info.getBytes());
	
		System.out.println(securityInfo);
		System.out.println("匹配结果"+validMd5(securityInfo, source));
		
	
	}

}
